package com.net.framework.help.utils;

import org.json.JSONException;
import org.json.JSONObject;

import java.lang.reflect.Field;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;

public class JSONBeanUtil {
	private static final String GET_PREFIX = "get";

	/**
	 * 将传入对象转换成JSONObject对象(key=对象定义的属性名称,value=属性对应的值)
	 * 
	 * @param object
	 *            需要转换的对象
	 * @return
	 */
	@SuppressWarnings("unchecked")
	public static JSONObject convertToJSONObject(Object object) {
		JSONObject result = new JSONObject();
		if (object != null) {
			try {
				Class objClazz = object.getClass();
				Field[] fields = objClazz.getDeclaredFields();
				if (fields != null && fields.length > 0) {
					for (int i = 0; i < fields.length; i++) {
						Field field = fields[i];
						String fname = field.getName();
						if (!"serialVersionUID".equals(fname)) {
							String methodName = GET_PREFIX + fname.substring(0, 1).toUpperCase() + fname.substring(1);
							Object retObj = objClazz.getMethod(methodName).invoke(object);
							if (retObj != null)
								result.put(field.getName(), objClazz.getMethod(methodName).invoke(object));
							else
								result.put(field.getName(), "");
						}
					}
				}
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
		return result;
	}

	public static JSONObject replaceNull(JSONObject targetObject) {
		JSONObject result = null;
		if (targetObject != null) {
			result = new JSONObject();
			Set<Map.Entry<String, Object>> entrySet = ((Map) targetObject).entrySet();
			Iterator<Map.Entry<String, Object>> iterator = entrySet.iterator();
			while (iterator.hasNext()) {
				Map.Entry<String, Object> entryData = iterator.next();
				String dataKey = entryData.getKey();
				Object dataValue = entryData.getValue();
				if (dataValue == null || "null".equals(dataValue))
					dataValue = "";
				try {
					result.put(dataKey, dataValue);
				} catch (JSONException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
		}
		return result;
	}
}
